const express = require("express");
const { MongoClient, ObjectId } = require("mongodb");
const dbClient = new MongoClient("mongodb://127.0.0.1:27017");

async function getArticleCollection() {
  await dbClient.connect();
  return dbClient.db("test").collection("articles");
}

const app = express();
// 配置解析请求体数据 application/json
// 它会把解析到的请求体数据放到 req.body 中
// 注意：一定要在使用之前就挂载这个中间件
app.use(express.json());

app.get("/", (req, res) => {
  res.send("Hello Worl！");
});

app.post("/articles", async (req, res, next) => {
  try {
    // console.log(req.body)
    // 1.获取客户端表单数据
    const { article } = req.body;
    // console.log(article)
    // 2.数据验证
    if (!article || !article.title || !article.description || !article.body) {
      return res.status(422).json({
        error: "请求参数不符合规则要求",
      });
    }
    // 3.把验证通过的数据插入数据库中
    // 成功==》发送成功响应
    // 失败==》发送失败响应
    // await dbClient.connect();
    // const collection = dbClient.db("test").collection("articles");
    const collection = await getArticleCollection();
    console.log(collection);
    const result = collection.insertOne(article);
    // console.log(result)
    article.createAt = new Date();
    article.updateAt = new Date();
    article._id = (await result).insertedId;
    // res.send('post /articles')
    res.status(201).json({
      article,
    });
  } catch (err) {
    next(err);
    // res.status(500).json({
    //   error: err.message,
    // });
  }
});

app.get("/articles", async (req, res, next) => {
  //   res.send("get /articles");
  try {
    const { page = 1, size = 10 } = req.query;
    const collection = await getArticleCollection();
    const articles = await collection
      .find() // 查询数据
      .skip((page - 1) * size) // 跳过多少条
      .limit(size * 1) // 取多少条
      .toArray();
    const articlesCount = await collection.countDocuments();
    res.status(200).json({
      articles,
      articlesCount,
    });
  } catch (err) {
    next(err);
  }
  //   const result = await collection.find()
  //   res.status(200).json({
  //     result: await result.toArray()
  //   })
});

app.get("/articles/:id", async (req, res) => {
  //   res.send("get /articles/:id");
  const { id } = req.params;
  const collection = await getArticleCollection();
  //   console.log(ObjectId(id))
  const result = await collection.findOne({
    _id: ObjectId(id),
  });
  res.status(200).json({
    result,
  });
});

// 更新文章
app.patch("/articles/:id", async (req, res) => {
  //   res.send("patch /articles/:id");
  const { id } = req.params;
  const article = req.body;
  const collection = await getArticleCollection();
  //   const result = await collection.updateOne(
  const result = await collection.replaceOne(
    {
      _id: ObjectId(id),
    },
    {
      article,
    }
  );
  res.status(200).json({
    result,
  });
});

app.delete("/articles/:id", async (req, res) => {
  //   res.send("delete /articles/:id");
  const { id } = req.params;
  const collection = await getArticleCollection();
  const result = await collection.deleteOne({
    _id: ObjectId(id),
  });
  res.status(200).json({
    result,
  });
});

// 它之前的所有路由中调用 next(err) 就会进入这里
// 注意：4个参数，缺一不可
app.use((err, req, res, next) => {
  res.status(500).json({
    error: err.message,
  });
});
app.listen(3000, () => {
  console.log("app listening at port 3000");
});
